import 'package:flutter/cupertino.dart';
import 'package:flutter_mvvm_demo/base/base_view_model.dart';
import 'package:flutter_mvvm_demo/page/home/model/home_product_model.dart';
import 'package:flutter_mvvm_demo/page/home/service/home_service.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomeViewModel extends BaseViewModel {
  HomeViewModel(BuildContext context) : super(context);

  /// 页数
  int _page = 0;

  int get page => _page;

  set page(int page) {
    _page = page;
  }

  /// 列表数据
  List<HomeProductModel> _dataList = [];

  List<HomeProductModel> get dataList => _dataList;

  set dataList(List<HomeProductModel> arr) {
    _dataList = arr;
    notifyListeners();
  }

  /// 刷新 controller
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  RefreshController get refreshController => _refreshController;

  /// 刷新数据
  @override
  Future refreshData({bool isShowLoading = false}) async {
    isLoading = isShowLoading;
    if (page == 0) {
      _dataList.clear();
      HomeService.getHomeList().then((data) {
        _dataList.addAll(data);
        page++;
        isLoading = false;
        notifyListeners();
      }).catchError((e) {
        debugPrint("======获取首页列表异常$e");
      });
      _refreshController.refreshCompleted();
    } else {
      await Future.delayed(const Duration(milliseconds: 1000));
      HomeService.getHomeList().then((data) {
        _dataList.addAll(data);
        _page++;
        isLoading = false;
        notifyListeners();
      }).catchError((e) {
        debugPrint("======获取首页列表异常$e");
      });
      _refreshController.loadComplete();
    }
  }
}
